package com.xudu.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.xudu.entity.StudentScore;
import com.xudu.mapper.StudentScoreMapper;
import com.xudu.service.IStudentScoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xudu.utils.CalculateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import sun.font.TrueTypeFont;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xudu
 * @since 2024-04-25
 */

@Service
@Slf4j
public class StudentScoreServiceImpl extends ServiceImpl<StudentScoreMapper, StudentScore> implements IStudentScoreService {

    @Autowired
    private StudentScoreMapper studentScoreMapper;

    @Override
    public double calculateAverageGrade(String subject) {
        //统计学生人数
        List<StudentScore> scores = studentScoreMapper.selectList(null);
        //List<Double> studentScores = studentScoreMapper.selectBySubject(subject);
        // 创建一个列表用于存储成绩
        List<Double> englishScores = new ArrayList<>();


        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        CalculateUtil calculate = new CalculateUtil();

        // 遍历成绩列表
        for (StudentScore score : scores) {
            pool.submit(() -> {
                // 将英语成绩添加到列表中
                log.info("{}在运行……", Thread.currentThread().getName());
                //englishScores.add(score.getEnglish());
                if (subject.equals("chinese")) {
                    calculate.addGrade(score.getChinese());
                } else if (subject.equals("math")) {
                    calculate.addGrade(score.getMath());
                } else {
                    calculate.addGrade(score.getEnglish());
                }

            });
        }


        // 计算平均分
//        for (Double score : englishScores) {
//            pool.submit(()->{
//                calculate.addGrade(score);
//            });
//
//        }

        // 关闭线程池
        pool.shutdown();
        try {
            // 等待所有任务完成
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                // 超时后可以选择取消所有任务
                pool.shutdownNow();
            }
        } catch (Exception e) {
            // 处理中断异常
            pool.shutdownNow();
            Thread.currentThread().interrupt(); // 重设中断状态
        }


        return calculate.getAverageGrade(scores.size());
    }

    //通过异步注解实现异步
    @Async
    @Override
    public void calculateOrUpdateSum() {
        // 查询所有学生记录
        List<StudentScore> scores = studentScoreMapper.selectList(null);
        for (StudentScore score : scores) {
            // 计算总分
            double totalScore = score.getChinese() + score.getMath() + score.getEnglish();
            score.setSum(totalScore);
            // 计算或更新数据库中的学生记录
            studentScoreMapper.updateById(score);
        }
    }

    /**
     * CompletableFuture
     */
    @Override
    public void calculateOrUpdateSum2() {
        // 查询所有学生记录
        List<StudentScore> scores = studentScoreMapper.selectList(null);

        for (StudentScore score : scores) {
            CompletableFuture.runAsync(() -> {
                // 计算总分
                double totalScore = score.getChinese() + score.getMath() + score.getEnglish();
                score.setSum(totalScore);
                // 计算或更新数据库中的学生记录
                studentScoreMapper.updateById(score);
                log.info(Thread.currentThread().getName() + "正在执行……");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }

    }


    /**
     * ThreadUtil实现异步
     */
    @Override
    public void calculateOrUpdateSum1() {
        // 查询所有学生记录
        List<StudentScore> scores = studentScoreMapper.selectList(null);
        for (StudentScore score : scores) {
            ThreadUtil.execute(() -> {
                // 计算总分
                double totalScore = score.getChinese() + score.getMath() + score.getEnglish();
                score.setSum(totalScore);
                // 计算或更新数据库中的学生记录
                studentScoreMapper.updateById(score);
                log.info(Thread.currentThread().getName() + "正在执行……");
            });
        }
    }


}
